import _ from 'lodash';
import moment from 'moment';
import { nanoid } from 'nanoid';
import { encryptParams } from '@/utils/crypto';
import { REACT_PUBLIC_KEY } from '@/utils/public_key';
import { REACT_APP_PARAMS_AES_KEY } from '@/utils/crypto';
import { sm2, sm3 } from 'sm-crypto';

// 报文加密
export const getEncryptData = (data) =>
  _.isString(data) ? encryptParams(data) : encryptParams(JSON.stringify(data || {}));
// 签名获取
export const getSignOptions = () => {
  const nonce = nanoid(16);
  const timestamp = moment().valueOf().toString();
  const signature = sm3(`timestamp=${timestamp}&nonce=${nonce}&secret=${REACT_APP_PARAMS_AES_KEY}`)
    .toString()
    .toUpperCase();
  return { timestamp, nonce, signature };
};

export default [
  async (url, options) => {
    const encryptAsyKey = '04' + sm2.doEncrypt(REACT_APP_PARAMS_AES_KEY, REACT_PUBLIC_KEY, 1);
    const { skipEncrypt } = options;
    const isEmptyParams = _.isEmpty(options.data);
    if (ENCRYPTION_PARAMS && !skipEncrypt && !isEmptyParams) {
      options.data = getEncryptData(options.data);
    }
    options.headers = _.assign({}, options.headers, getSignOptions(), {
      aesKey: encryptAsyKey,
    });
    return Promise.resolve();
  },
];
